import api from "../../../../../common/api";
import mapConfig from "../../../../../utils/mapConfig";
import locationBehavior from "../../../../../behaviors/location";
import * as transferData from "../../../../../models/transferData";
import { authorizationBehavior, SCOPE_USERLOCATION } from "../../../../../behaviors/authorization";

let qqmapsdk = mapConfig.qqmapsdk;
const app = getApp();

Page({
  behaviors: [locationBehavior, authorizationBehavior],
  data: {
    firstEnter: true,
    city: "",
    latitude: "",
    longitude: "",
    markers: [
      {
        iconPath: "/images/marker.png",
        id: 0,
        latitude: "",
        longitude: "",
        width: 20,
        height: 20,
      },
    ],
    rows: [],
    loading: false,
    scale: 16,
    isChoseCity: false,
    subscription: true,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.mobileLogin().then(() => {
      wx.showLoading();
      this.getRecordAuthorize(SCOPE_USERLOCATION)
        .then(() => {
          return this.loacalMapRefresh();
        })
        .then(() => {
          wx.hideLoading();
        });
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */

  onShow: function () {
    if (this.data.firstEnter) {
      this.data.firstEnter = false;
      return;
    }
    this.renderCityFromStorage();
  },

  // 从缓存中更新城市
  renderCityFromStorage() {
    var currentCity = wx.getStorageSync("currentCity");
    if (currentCity && currentCity.city) {
      this.setData({ city: currentCity.city });

      if (currentCity.city == this.data.$cityReality.city) {
        this.loacalMapRefresh();
      } else {
        qqmapsdk.geocoder({
          address: currentCity,
          success: (res) => {
            let { lat, lng } = res.result.location;
            this.renderByLatLng(lat, lng);
          },
        });
      }
    }
  },

  // 渲染列表数据
  renderList(rows) {
    if (rows.length == 0) {
      return this.setData({ rows });
    }
    let rowIds = rows.map((v) => v.hdResblockId);
    api.houseOwnerSubscribeList(rowIds, (res) => {
      let content = res.data.content;
      rows.forEach((n) => {
        let isSubscribe = content.find((o) => o == n.hdResblockId);
        n.subscribe = !!isSubscribe;
      });

      this.setData({ rows });
    });
  },

  // 视野发生变化时触发 获取中心点（即用户选择的位置）
  regionchange(e) {
    //只有拖动的情况下
    if (e.causedBy == "drag") {
      let that = this;
      that.mapCtx = wx.createMapContext("map");
      that.mapCtx.getCenterLocation({
        success: ({ latitude, longitude }) => {
          this.renderByLatLng(latitude, longitude);
        },
      });
    }
  },

  // 通过经纬度 渲染列表数据、渲染城市、渲染地图
  renderByLatLng(lat, lng, reality = false) {
    this.setData({ loading: true });
    this.renderMap(lat, lng);
    return this.getCurrentCityByLatlng(lat, lng, reality)
      .then((res) => {
        this.setData({ city: res.city });
        return this.getVillageBe(res, this.data.subscription);
      })
      .then((rows) => {
        this.renderList(rows);
        this.setData({ loading: false });
      });
  },

  renderMap(lat, lng) {
    this.setData({
      latitude: lat,
      longitude: lng,
      markers: [
        {
          iconPath: "/images/marker.png",
          id: 0,
          latitude: lat,
          longitude: lng,
          width: 20,
          height: 20,
        },
      ],
    });
  },

  goSearchHouse() {
    wx.navigateTo({
      url: `../searchHouse/searchHouse?subscribe=1`,
    });
  },
  //选择城市
  goSwitchCity() {
    wx.navigateTo({
      url: "/pages/home/switchCity/switchCity",
    });
  },

  // 本地地图刷新 （已经授权了地理坐标的前提下）
  loacalMapRefresh() {
    return this.getWxLocationBe().then(({ latitude, longitude }) => {
      return this.renderByLatLng(latitude, longitude, true);
    });
  },

  getSubscribe(e) {
    let sub = e.currentTarget.dataset.sub;
    let hdResblockId = e.currentTarget.dataset.hdresblockid;
    if (sub === '0') {
      wx.showLoading({
        title: '取消订阅...',
      })
    } else {
      wx.showLoading({
        title: '订阅中...',
      })
    }
    api.doSubscribeResblock(
      {
        hdResblockId,
        isSubscribe: sub,
      },
      (res) => {
        wx.hideLoading();
        const { rows } = this.data;
        transferData.setData("isRefreshMySubscribe", true);
        if(res.data.errorCode==='31001'){ //无该小区
          wx.showModal({
            title: '温馨提示',
            content: '该小区暂不支持订阅',
            confirmText: '联系客服',
            cancelText: '关闭',
            confirmColor: '#F75352',
            success(res) {
              if (res.confirm) {
                api.getPrivateSale({}, (res1) => {
                  wx.makePhoneCall({
                    phoneNumber: res1.data.content.serviceMobile,
                    success() {},
                    fail() {},
                  });
                });
              }
            },
          })
        } else {
          rows.forEach(item => {
            if(item.hdResblockId === hdResblockId) {
              item.subscribe = sub == 1 ? true : false
            }
          })
        }
        this.setData({
          rows,
        });
      }
    );
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
});
